package com.ekuaitu.kuaitu.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.CityDetailBean;
import com.ekuaitu.kuaitu.bean.DropOffBikeBean;
import com.ekuaitu.kuaitu.bean.JudgmentBean;
import com.ekuaitu.kuaitu.bean.OrderDetailBean;
import com.ekuaitu.kuaitu.bean.QueryLockBean;
import com.ekuaitu.kuaitu.bean.RedBikeHotSpotInfoBean;
import com.ekuaitu.kuaitu.bean.ResultBean;
import com.ekuaitu.kuaitu.bean.UnFinishOrderBean;
import com.ekuaitu.kuaitu.ble.BluetoothHelper;
import com.ekuaitu.kuaitu.ble.ClientManager;
import com.ekuaitu.kuaitu.map.MarkerUtils;
import com.ekuaitu.kuaitu.map.PolylineBoundUtils;
import com.ekuaitu.kuaitu.map.SensorEventHelper;
import com.ekuaitu.kuaitu.utils.AppManager;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.DensityUtils;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.IntentUtils;
import com.ekuaitu.kuaitu.utils.KuaituDialog;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.NetUtils;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.TimeUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.amap.api.fence.GeoFenceClient.GEOFENCE_IN;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_OUT;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_STAYED;

public class BikeInUseRedActivity extends AppCompatActivity implements AMapLocationListener, AMap.OnMarkerClickListener, View.OnClickListener {
    private MapView mapView;
    private ImageView ivRefresh;
    //骑行计时
    private TextView tvDuration;
    //结算
    private TextView tvReturn;
    //申报故障
    private TextView tvReport;
    //开不了锁?
    private LinearLayout layoutRepair;
    //开锁
    private LinearLayout layoutScanOpen;
    //进度条
    private RelativeLayout rlProgressBar;
    private TextView tvBikeId;
    //底部布局
    private LinearLayout bottomLayout;
    private LinearLayout dragView;
    private ImageView ivArrow;


    private AMap aMap;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private MarkerUtils markerUtils;
    private Marker locationMarker;
    private PolylineBoundUtils polylineBoundUtils;
    private SensorEventHelper mSensorHelper;
    public static LatLng curPosition;
    private Context mContext = this;
    private Boolean isFirstLocation = true;
    public static AMapLocation aMapLocation;
    private int power;
    private int caozuo = -1;

    private List<Polygon> coverPolygon;
    private List<Polygon> boundPolygon;
    private CityDetailBean.AttachmentBean.EnclosureBean cityInfo;

    private GeoFenceClient mGeoFenceClient;
    //定义接收广播的action字符串
    public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";

    private TimerTask task;
    private Timer timer;
    private long heatCount;
    private long count = 0;
    private boolean isSendHeat;
    private PowerManager.WakeLock wakeLock;

    private PopupWindow popupWindow;

    private String orderId;
    private String bikeId;
    private int lockType;
    private String btMac;
    private boolean isExit = false;
    private String bikeLicense;
    //定位后的动作类型
    private int locationOptype;
    private boolean isReturnBike = false;

    byte[] loadPwd = new byte[6];
    byte[] loadKey = new byte[16];

    //动画相关
    private Scroller mScroller;
    private int mLastFlingX = 0;
    private final Runnable mScrollRun = new Runnable() {

        @Override
        public void run() {

            if (mScroller.isFinished()) {
                return;
            }
            final boolean more = mScroller.computeScrollOffset();
            final int y = mScroller.getCurrY();
            final int diff = mLastFlingX - y;
            if (diff != 0) {
                bottomLayout.scrollBy(0, diff);
                mLastFlingX = y;
            }
            if (more) {
                bottomLayout.post(mScrollRun);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bike_in_use_red);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary), 0, false);
        mapView = (MapView) findViewById(R.id.bike_red_inuse_map);
        mapView.onCreate(savedInstanceState);
        mScroller = new Scroller(this);
        initView();
        initData();
        initWeilanClient();
        initMap();
        getLocationPermission();
    }

    private void initView() {
        ivRefresh = (ImageView) findViewById(R.id.imageView_refresh);
        tvDuration = (TextView) findViewById(R.id.red_bike_inuse_tvDuration);
        tvReturn = (TextView) findViewById(R.id.red_bike_inuse_tvReturn);
        tvReport = (TextView) findViewById(R.id.red_bike_inUse_report);
        layoutRepair = (LinearLayout) findViewById(R.id.red_bike_inuse_llrepair);
        layoutScanOpen = (LinearLayout) findViewById(R.id.red_bike_inuse_llScan);
        rlProgressBar = (RelativeLayout) findViewById(R.id.red_progressBar_bike_inUse);
        tvBikeId = (TextView) findViewById(R.id.red_bike_inuse_bikeid);
        bottomLayout = (LinearLayout) findViewById(R.id.bike_inuse_bottom_layout);
        dragView = (LinearLayout) findViewById(R.id.red_bike_inuse_dragview);
        ivArrow = (ImageView) findViewById(R.id.red_bike_inuse_arrow);

        ivRefresh.setOnClickListener(this);
        tvReturn.setOnClickListener(this);
        layoutRepair.setOnClickListener(this);
        layoutScanOpen.setOnClickListener(this);
        tvReport.setOnClickListener(this);
        dragView.setOnClickListener(this);
    }

    private void initData() {
        Intent intent = getIntent();
        orderId = intent.getStringExtra(IntentKey.INTENT_ORDER_ID);
        btMac = intent.getStringExtra("btMac");
        lockType = intent.getIntExtra(IntentKey.INTENT_LOCK_TYPE, -1);
        getOrderDetail(orderId);

        bottomLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mScroller.isFinished() && bottomLayout.getScrollY() == 0) {
                    scrollDown(bottomLayout.getHeight() - (getResources().getDimensionPixelSize(R.dimen.dimen_10) * 5 + dragView.getHeight()));
                }
            }
        }, 5000);
    }

    private void scrollUp(int distance) {
        mScroller.startScroll(0, bottomLayout.getScrollY(), 0, distance, 500);
        mLastFlingX = bottomLayout.getScrollY();
        bottomLayout.post(mScrollRun);
        ivArrow.setImageResource(R.drawable.arrow_group_close);
    }

    private void scrollDown(int distance) {
        mScroller.startScroll(0, 0, 0, distance, 500);
        mLastFlingX = bottomLayout.getScrollY();
        bottomLayout.post(mScrollRun);
        ivArrow.setImageResource(R.drawable.arrow_group_open);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_refresh:
                if (curPosition != null) {
                    aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 16, 0, 0)), 700, null);
                }
                break;
            case R.id.red_bike_inuse_tvReturn:
                caozuo = 0;
                locationOptype = 0;//标记定位后的操作类型
                if (curPosition != null) {
                    requestIsInRedpacketPot();
                } else {
                    ToastCompat.makeText(mContext, "正在获取您的位置信息...", Toast.LENGTH_LONG).show();
                }

                break;
            case R.id.red_bike_inUse_report:
                Intent intent = new Intent();
                intent.setClass(mContext, ComplaintsActivity.class);
                if (orderId != null) {
                    intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                }
                intent.putExtra(IntentKey.INTENT_TRIP_MODE, 2);
                intent.putExtra("licenseTag", bikeLicense);
                startActivity(intent);
                break;
            case R.id.red_bike_inuse_llrepair:
                locationOptype = 1;
                rlProgressBar.setVisibility(View.VISIBLE);
                getLocationPermission();
                break;
            case R.id.red_bike_inuse_llScan:
                getUnFinishOrder();
                MobclickAgent.onEvent(BikeInUseRedActivity.this, Constants.RIDINGOPENLOCK);
                break;
            case R.id.red_bike_inuse_dragview:
                if (bottomLayout.getScrollY() == 0 && mScroller.isFinished()) {
                    scrollDown(bottomLayout.getHeight() - (getResources().getDimensionPixelSize(R.dimen.dimen_10) * 5 + dragView.getHeight()));
                } else if (mScroller.isFinished()) {
                    scrollUp(bottomLayout.getScrollY());
                }
                break;
        }
    }

    /**
     * 实例化地理围栏客户端
     */
    private void initWeilanClient() {
        mGeoFenceClient = new GeoFenceClient(getApplicationContext());
        mGeoFenceClient.setActivateAction(GEOFENCE_IN | GEOFENCE_OUT | GEOFENCE_STAYED);
        //创建并设置PendingIntent
        mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);

        //注册围栏广播
        IntentFilter fliter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        fliter.addAction(GEOFENCE_BROADCAST_ACTION);
        registerReceiver(mGeoFenceReceiver, fliter);
    }

    private void getLocationPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                startLocation();
            }
        } else {
            startLocation();
        }
    }

    private void startLocation() {
        mLocationClient.startLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        heatCount = 0;
        isSendHeat = true;
        mapView.onResume();
        initSensor();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        if (!TextUtils.isEmpty(btMac)) {
            BluetoothHelper.getInstance().resetNotifyCallback(btMac);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        heatCount = 0;
        isSendHeat = false;
    }

    public void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            //设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(false);
            aMap.setMapType(AMap.MAP_TYPE_NAVI);
            //设置点击marker事件监听器
            aMap.setOnMarkerClickListener(this);
            UiSettings uiSettings = aMap.getUiSettings();
            //设置地图交互
            uiSettings.setMyLocationButtonEnabled(false);
            uiSettings.setScaleControlsEnabled(false);
            uiSettings.setRotateGesturesEnabled(false);
            uiSettings.setZoomControlsEnabled(false);
            uiSettings.setScrollGesturesEnabled(true);
            uiSettings.setZoomGesturesEnabled(true);
            uiSettings.setTiltGesturesEnabled(false);

            //设置定位的参数
            if (mLocationClient == null) {
                mLocationClient = new AMapLocationClient(getApplicationContext());
                mLocationOption = new AMapLocationClientOption();
                //设置定位监听
                mLocationClient.setLocationListener(this);
                //设置为高精度定位模式
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                mLocationOption.setInterval(2000);
                //设置定位参数
                mLocationClient.setLocationOption(mLocationOption);
            }
            markerUtils = new MarkerUtils(mContext, aMap);
            polylineBoundUtils = new PolylineBoundUtils(aMap);

            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    //backPress(false);
                }
            });

            aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                @Override
                public void onCameraChange(CameraPosition cameraPosition) {
                    if (cityInfo != null) {
                        if (cameraPosition.zoom < 14.5 && coverPolygon == null) {
                            coverPolygon = polylineBoundUtils.addCoversToMap(cityInfo.getBikeRangeList());
                        } else if (cameraPosition.zoom >= 14.5 && coverPolygon != null) {
                            for (int i = 0; i < coverPolygon.size(); i++) {
                                coverPolygon.get(i).remove();
                            }
                            coverPolygon = null;
                        }
                    }
                }

                @Override
                public void onCameraChangeFinish(CameraPosition cameraPosition) {
                }
            });
        }
    }

    //获取城市信息
    public void getCityInfo() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getCityInfo(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<CityDetailBean>() {
                    @Override
                    public void onResponse(Call<CityDetailBean> call, Response<CityDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getAttachment() != null) {
                            if (response.body().getStatus() == 400) {

                            } else if (response.body().getStatus() == 200) {
                                cityInfo = response.body().getAttachment().getEnclosure();
                                boundPolygon = polylineBoundUtils.addBoundsToMap(cityInfo.getBikeRangeList());
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            if (SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.USER_PHONE_NUM) != null) {  //是否登录
                                aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 18, 0, 0)), 700, null);
                            } else {  //未登录
                                aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 18, 0, 0)), 700, null);
                            }
                            //getGeofenceInfos();
                        }
                    }

                    @Override
                    public void onFailure(Call<CityDetailBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                        Log.i("netError", "002");
                    }
                });
    }

    /***
     * 获取多边形围栏数据
     */
    private void getGeofenceInfos() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getRedPacketHotList(MyApplication.getInstance().getRequestFieldMap(), curPosition.latitude + "", curPosition.longitude + "")
                .enqueue(new Callback<RedBikeHotSpotInfoBean>() {
                    @Override
                    public void onResponse(Call<RedBikeHotSpotInfoBean> call, Response<RedBikeHotSpotInfoBean> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getAttachment() != null) {
                            if (response.body().getStatus() == 200) {
                                List<RedBikeHotSpotInfoBean.AttachmentBean> geoFenceList = response.body().getAttachment();
                                addBoundsToMap(geoFenceList);
                                //addGeoFenceToMap(geoFenceList);
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<RedBikeHotSpotInfoBean> call, Throwable t) {

                    }
                });
    }

    public List<Polygon> addBoundsToMap(List<RedBikeHotSpotInfoBean.AttachmentBean> geoFenceList) {
        List<Polygon> polygonList = new ArrayList<>();
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (curPosition != null) {
            b.include(curPosition);
        }

        for (int i = 0; i < geoFenceList.size(); i++) {
            polygonList.add(aMap.addPolygon(new PolygonOptions().addAll(createBound(geoFenceList.get(i).getPointList())).fillColor(Color.parseColor("#33FA960A")).strokeColor(Color.parseColor("#FA960A")).strokeWidth(6)));

            if ((geoFenceList.get(i).getBusinessName() != null && !geoFenceList.get(i).getBusinessName().equals(""))) {
                new MarkerUtils(mContext, aMap).addBrandMarkerToMap(geoFenceList.get(i).getBusinessLatitude(), geoFenceList.get(i).getBusinessLongitude(),
                        geoFenceList.get(i).getBusinessName(), geoFenceList.get(i).getBusinessImg(), null);
            }
            b.include(new LatLng(geoFenceList.get(i).getCenterLatitude(), geoFenceList.get(i).getCenterLongitude()));
            //缩放地图
            aMap.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(
                    b.build(),
                    DensityUtils.dp2px(mContext, 50), DensityUtils.dp2px(mContext, 50), DensityUtils.dp2px(mContext, 50), DensityUtils.dp2px(mContext, 50)),
                    400,
                    null);
        }
        return polygonList;
    }

    //向地图中加入电子围栏数据
    public void addGeoFenceToMap(List<RedBikeHotSpotInfoBean.AttachmentBean> geoFenceList) {
        for (int i = 0; i < geoFenceList.size(); i++) {
            RedBikeHotSpotInfoBean.AttachmentBean geoFence = geoFenceList.get(i);
            mGeoFenceClient.addGeoFence(createGeofenceInfos(geoFence.getPointList()), geoFence.getHotspotId());
        }
    }

    private List<LatLng> createBound(List<RedBikeHotSpotInfoBean.AttachmentBean.PointListBean> fencePoints) {
        List<LatLng> boundList = new ArrayList<>();
        for (int i = 0; i < fencePoints.size(); i++) {
            LatLng latLng = new LatLng(fencePoints.get(i).getLatitude(), fencePoints.get(i).getLongitude());
            boundList.add(latLng);
        }
        return boundList;
    }

    /**
     * 电子围栏数据
     *
     * @param fencePoints
     * @return
     */
    private List<DPoint> createGeofenceInfos(List<RedBikeHotSpotInfoBean.AttachmentBean.PointListBean> fencePoints) {
        List<DPoint> boundList = new ArrayList<>();
        for (int i = 0; i < fencePoints.size(); i++) {
            DPoint dPoint = new DPoint(fencePoints.get(i).getLatitude(), fencePoints.get(i).getLongitude());
            boundList.add(dPoint);
        }
        return boundList;
    }

    /**
     * 获取订单详情
     *
     * @param orderId
     */
    private void getOrderDetail(String orderId) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getOrderDetail(MyApplication.getInstance().getRequestFieldMap(), orderId)
                .enqueue(new Callback<OrderDetailBean>() {
                    @Override
                    public void onResponse(Call<OrderDetailBean> call, Response<OrderDetailBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                OrderDetailBean.AttachmentBean result = response.body().getAttachment();
                                bikeLicense = result.getBikeModel().getLicenseTag();
                                bikeId = result.getBikeModel().getBikeId();
                                bikeLicense = result.getBikeModel().getLicenseTag();
                                lockType = result.getBikeModel().getLockType();
                                tvBikeId.setText(bikeLicense);
                                Date date = new Date();
                                if (result.getStartBillingTime() <= 0) {
                                    count = 1;
                                } else {
                                    count = (int) ((date.getTime() - result.getStartBillingTime()) / 1000) + 1;
                                }
                                if (count < 0) {
                                    count = 1;
                                }
                                tvDuration.setText(TimeUtils.formatSecondCount(count + "", 1));
                                countTime();
                                getBikeType();
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<OrderDetailBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 获取单车的锁相关信息
     */
    private void getBikeType() {
        rlProgressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).requestBTBikeInfo(MyApplication.getInstance().getRequestFieldMap(), bikeId, "0")
                .enqueue(new Callback<QueryLockBean>() {
                    @Override
                    public void onResponse(Call<QueryLockBean> call, final Response<QueryLockBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            rlProgressBar.setVisibility(View.GONE);
                            if (response.body().getStatus() == 200) {
                                btMac = response.body().getAttachment().getBikeMachineUnique();
                                lockType = response.body().getAttachment().getLockType();
                                if (lockType == 2 || lockType == 3 || lockType == 4) {
                                    String key = response.body().getAttachment().getBikeMachineKey();
                                    String pwd = response.body().getAttachment().getBikeMachinePassword();
                                    String[] KEY = key.split(",");
                                    String[] PWD = pwd.split(",");
                                    for (int i = 0; i < 16; i++) {
                                        loadKey[i] = Byte.parseByte(KEY[i]);
                                    }
                                    for (int j = 0; j < 6; j++) {
                                        loadPwd[j] = Byte.parseByte(PWD[j]);
                                    }
                                    rlProgressBar.setVisibility(View.VISIBLE);
                                    ClientManager.getClient().registerBluetoothStateListener(mBluetoothStateListener);
                                    if (ClientManager.getClient().isBluetoothOpened()) {
                                        int status = ClientManager.getClient().getConnectStatus(btMac);
                                        if (status == 2) {
                                            BluetoothHelper.getInstance().loadLockData(btMac, MyApplication.btToken, loadPwd, loadKey);
                                            BluetoothHelper.getInstance().setBluetoothCommandCallback(commandCallback);//蓝牙指令回调
                                            rlProgressBar.setVisibility(View.GONE);
                                        } else {
                                            Log.i("saomiao", "未连接" + status);
                                            BluetoothHelper.getInstance().searchDevice(mSearchResponse, commandCallback);
                                        }
                                    } else {
                                        ClientManager.getClient().openBluetooth();
                                    }
                                    //查询电量
                                    BluetoothHelper.getInstance().checkDianLiang();
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            rlProgressBar.setVisibility(View.GONE);
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<QueryLockBean> call, Throwable t) {
                        rlProgressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //GPS还车
    private void dropOffBike(String longitude, String latitude) {
        commitBikeLogPre();
        rlProgressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).dropOffBike(MyApplication.getInstance().getRequestFieldMap(), orderId, bikeId, longitude,
                latitude, lockType + "", "", "0").enqueue(new Callback<DropOffBikeBean>() {
            @Override
            public void onResponse(Call<DropOffBikeBean> call, Response<DropOffBikeBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        String isPraise = response.body().getAttachment().getIsprize();
                        if ("1".equals(isPraise)) {
                            Intent intent = new Intent(mContext, CompleteRedActivity.class);
                            List<DropOffBikeBean.AttachmentBean.PrizeDetailBean> detailBeanList = response.body().getAttachment().getPrizeDetail();
                            if (detailBeanList != null && detailBeanList.size() > 0) {
                                intent.putExtra("couponsCount", detailBeanList.get(0).getCouponsCount());
                                intent.putExtra("prizeAmount", response.body().getAttachment().getPrizeMsg());
                            }
                            startActivity(intent);
                            finish();
                        } else if ("2".equals(isPraise)) {
                            final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseRedActivity.this);
                            kuaituDialog.setTitle(getString(R.string.dialogTitle));
                            kuaituDialog.setMessage("此次骑行将不收取费用。");
                            kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                                @Override
                                public void onYesClick() {
                                    kuaituDialog.dismiss();
                                    startActivity(new Intent(mContext, MainActivity.class));
                                    finish();
                                }
                            });
                            kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                @Override
                                public void onNoClick() {
                                    kuaituDialog.dismiss();
                                    finish();
                                }
                            });
                            kuaituDialog.setCancelable(false);
                            kuaituDialog.show();
                        } else {
                            IntentUtils.toSettlementActivity(BikeInUseRedActivity.this, orderId, bikeId);
                            finish();
                        }
                        commitBikeLogSuccess();
                    } else if (response.body().getStatus() == 404) {
                        ToastCompat.makeText(mContext, "您距离单车太远", Toast.LENGTH_LONG).show();
                        commitBikeLogFailed(404, "您距离单车太远");
                    } else if (response.body().getStatus() == 403) {
                        ToastCompat.makeText(mContext, "与单车通信失败", Toast.LENGTH_LONG).show();
                        commitBikeLogFailed(403, "与单车通信失败");
                    } else if (response.body().getStatus() == 400) {
                        ToastCompat.makeText(mContext, "还车失败", Toast.LENGTH_LONG).show();
                        commitBikeLogFailed(400, "还车失败");
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                        commitBikeLogFailed(response.body().getStatus(), response.body().getMessage());
                    }
                }
                rlProgressBar.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<DropOffBikeBean> call, Throwable t) {
                rlProgressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.dropOffBikeFailure), Toast.LENGTH_LONG).show();
            }
        });
    }

    private boolean isStartingDropOffBike = false;

    //蓝牙还车
    private void dropOffBTBike(String power, final String mac, String errorCode) {
        commitBikeLogPre();
        rlProgressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).dropOffBike(MyApplication.getInstance().getRequestFieldMap(), orderId, bikeId, curPosition.longitude + "",
                curPosition.latitude + "", lockType + "", power, errorCode)
                .enqueue(new Callback<DropOffBikeBean>() {
                    @Override
                    public void onResponse(Call<DropOffBikeBean> call, final Response<DropOffBikeBean> response) {
                        SharedPreferencesUtils.getInstance(BikeInUseRedActivity.this).putBooleanValue(Constants.LOCK_IS_CLOSE, false);
                        isStartingDropOffBike = false;
                        if (response.isSuccessful() && response.body() != null) {
                            rlProgressBar.setVisibility(View.GONE);
                            if (response.body().getStatus() == 200) {
                                ClientManager.getClient().disconnect(mac);
                                DropOffBikeBean.AttachmentBean attachmentBean = response.body().getAttachment();
                                String isPraise = null;
                                if (attachmentBean != null) {
                                    isPraise = attachmentBean.getIsprize();
                                }
                                if ("1".equals(isPraise)) {
                                    Intent intent = new Intent(mContext, CompleteRedActivity.class);
                                    List<DropOffBikeBean.AttachmentBean.PrizeDetailBean> detailBeanList = response.body().getAttachment().getPrizeDetail();
                                    if (detailBeanList != null && detailBeanList.size() > 0) {
                                        intent.putExtra("couponsCount", detailBeanList.get(0).getCouponsCount());
                                        intent.putExtra("prizeAmount", response.body().getAttachment().getPrizeMsg());
                                    }
                                    startActivity(intent);
                                    finish();
                                } else if ("2".equals(isPraise)) {
                                    final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseRedActivity.this);
                                    kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                    kuaituDialog.setMessage("此次骑行将不收取费用。");
                                    kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                                        @Override
                                        public void onYesClick() {
                                            kuaituDialog.dismiss();
                                            startActivity(new Intent(mContext, MainActivity.class));
                                            finish();
                                        }
                                    });
                                    kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                        @Override
                                        public void onNoClick() {
                                            kuaituDialog.dismiss();
                                            finish();
                                        }
                                    });
                                    kuaituDialog.setCancelable(false);
                                    kuaituDialog.show();
                                } else {
                                    IntentUtils.toSettlementActivity(BikeInUseRedActivity.this, orderId, bikeId);
                                    finish();
                                }
                                commitBikeLogSuccess();
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                                commitBikeLogFailed(response.body().getStatus(), response.body().getMessage());
                            }
                        } else {
                            rlProgressBar.setVisibility(View.GONE);
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_LONG).show();
                            commitBikeLogFailed(404, "服务器异常");
                        }
                    }

                    @Override
                    public void onFailure(Call<DropOffBikeBean> call, Throwable t) {
                        rlProgressBar.setVisibility(View.GONE);
                        isStartingDropOffBike = false;
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 是否在电子围栏内
     */
    private void requestIsInRedpacketPot() {
        rlProgressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).judgmentInPacketHotsPot(MyApplication.getInstance().getRequestFieldMap(), orderId, curPosition.latitude + "", curPosition.longitude + "")
                .enqueue(new Callback<JudgmentBean>() {
                    @Override
                    public void onResponse(Call<JudgmentBean> call, Response<JudgmentBean> response) {
                        rlProgressBar.setVisibility(View.GONE);
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {//在电子围栏内
                                returnBike();
                            } else {//不在热点区域内
                                String message = response.body().getAttachment().getMessage();
                                if (response.body().getStatus() == 401) {
                                    //未超过2次
                                } else if (response.body().getStatus() == 402) {
                                    //超过2次
                                }
                                //ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseRedActivity.this);
                                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                kuaituDialog.setMessage(message);
                                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        returnBike();
                                        kuaituDialog.dismiss();
                                    }
                                });
                                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        kuaituDialog.dismiss();
                                    }
                                });
                                kuaituDialog.setCancelable(false);
                                kuaituDialog.show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<JudgmentBean> call, Throwable t) {
                        rlProgressBar.setVisibility(View.GONE);
                    }
                });
    }

    /**
     * 结束行程，去结算
     */
    private void returnBike() {
        isReturnBike = true;
        if (lockType == 1) {
            dropOffBike(aMapLocation.getLongitude() + "", aMapLocation.getLatitude() + "");
        } else if (lockType == 2 || lockType == 3 || lockType == 4) {
            boolean isClose = SharedPreferencesUtils.getInstance(this).getBooleanValue(Constants.LOCK_IS_CLOSE);
            //如果已经关闭的锁则直接还车
            if (isClose) {
                dropOffBTBike(power + "", btMac, "0");
            } else if (ClientManager.getClient().isBluetoothOpened()) {
                int status = ClientManager.getClient().getConnectStatus(btMac);
                Log.i("========还车连接状态========>", status + " mac" + BluetoothHelper.getInstance().getCurrentConnectMac());
                //如果蓝牙已经连接，直接发送数据；未连接则开始搜索蓝牙。
                if (BluetoothHelper.getInstance().isConnect()) {
                    if (BluetoothHelper.getInstance().connectTokenIsEmpty()) {
                        isReturnBike = false;
                        ToastCompat.makeText(BikeInUseRedActivity.this, "没有和单车建立正确的连接，还车失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    BluetoothHelper.getInstance().checkStatus();
                } else {
                    BluetoothHelper.getInstance().searchDevice(mSearchResponse, commandCallback);
                }

            } else {
                ClientManager.getClient().openBluetooth();
            }
        }
    }

    //关锁后提交位置信息
    private void closeLockSendLocation() {
        SharedPreferencesUtils.getInstance(this).putBooleanValue(Constants.LOCK_IS_CLOSE, true);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).closeLockSendLocation(MyApplication.getInstance().getRequestFieldMap(), bikeId, bikeLicense,
                curPosition.longitude + "", curPosition.latitude + "", orderId).enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {

            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 获取未完成订单
     */
    private void getUnFinishOrder() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getUnFinishOrder(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<UnFinishOrderBean>() {
                    @Override
                    public void onResponse(Call<UnFinishOrderBean> call, final Response<UnFinishOrderBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                if (response.body().getAttachment().getIsUnfinished() != 0) {
                                    if (response.body().getAttachment().getStatus() == 15) {
                                        orderId = response.body().getAttachment().getOrderId();
                                        bikeId = response.body().getAttachment().getOrderModel().getBikeModel().getBikeId();
                                        final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseRedActivity.this);
                                        kuaituDialog.setTitle(getString(R.string.dialogTitle));
                                        kuaituDialog.setMessage("您已还车，请去结算");
                                        kuaituDialog.setYesOnclickListener("支付", new KuaituDialog.onYesOnclickListener() {
                                            @Override
                                            public void onYesClick() {
                                                IntentUtils.toSettlementActivity(BikeInUseRedActivity.this, orderId, bikeId);
                                                finish();
                                                kuaituDialog.dismiss();
                                            }
                                        });
                                        kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                                            @Override
                                            public void onNoClick() {
                                                kuaituDialog.dismiss();
                                            }
                                        });
                                        kuaituDialog.setCancelable(false);
                                        kuaituDialog.show();
                                    } else if (response.body().getAttachment().getStatus() == 10) {
                                        getCameraPermission();
                                    } else {
                                        Intent intent = new Intent(mContext, MainActivity.class);
                                        intent.putExtra("isLogin", true);
                                        startActivity(intent);
                                        finish();
                                    }
                                } else {  //没有未完成订单
                                    Intent intent = new Intent(mContext, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<UnFinishOrderBean> call, Throwable t) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void initSensor() {
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        } else {
            mSensorHelper = new SensorEventHelper(this);
            mSensorHelper.registerSensorListener();
            if (mSensorHelper.getCurrentMarker() == null && locationMarker != null) {
                mSensorHelper.setCurrentMarker(locationMarker);
            }
        }
    }

    private void getCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constants.READ_CAMERA_PERMISSION_REQUEST);
            } else {
                intentScanBike();
            }
        } else {
            intentScanBike();
        }
    }

    //跳转扫码页面
    private void intentScanBike() {
        Intent intent = new Intent(mContext, ScanBikeQrActivity.class);
        intent.putExtra(IntentKey.INTENT_BIKE_ID, bikeId);
        intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
        intent.putExtra(IntentKey.INTENT_BIKE_LICENSE_DESIGNATED, bikeLicense);
        intent.putExtra(IntentKey.INTENT_LOCK_TYPE, lockType);
        intent.putExtra("requestCode", Constants.REQUEST_SCAN_INUSE);
        startActivity(intent);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            this.aMapLocation = aMapLocation;
            // 更新定位
            curPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            Log.i("curPosition", curPosition.toString());
            if (locationOptype == 0) {
                if (isFirstLocation) {//首次定位
                    aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(curPosition, 16, 0, 0)));
                    locationMarker = markerUtils.addLocationIcon(curPosition);
                    //mCircle = polylineBoundUtils.addCircle(curPosition, amapLocation.getAccuracy());//添加定位精度圆
                    locationMarker.setClickable(false);
                    mSensorHelper.setCurrentMarker(locationMarker);
                    if (aMapLocation.getCityCode() != null && !aMapLocation.getCityCode().equals("")) {
                        MyApplication.getInstance().setAreaCode(aMapLocation.getCityCode());
                        getCityInfo();//获取城市信息
                    }
                    isFirstLocation = false;
                } else {
                    locationMarker.setPosition(curPosition);
                    //mCircle.setCenter(curPosition);
                    //mCircle.setRadius(amapLocation.getAccuracy());
                }
            } else if (locationOptype == 1) {//跳转修复车锁
                rlProgressBar.setVisibility(View.GONE);
                if (curPosition != null) {
                    Intent intent = new Intent(mContext, RepairBTBikeActivity.class);
                    intent.putExtra("bikeLicense", bikeLicense);
                    intent.putExtra(IntentKey.INTENT_BIKE_ID, bikeId);
                    intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                    if (lockType == 2 || lockType == 3 || lockType == 4) {
                        intent.putExtra("mac", btMac);
                    }
                    intent.putExtra(IntentKey.INTENT_LOCK_TYPE, lockType);
                    startActivity(intent);
                }
            }
            locationOptype = -1;
        } else {
            if (isFirstLocation) {
                String errText = "定位失败";
                ToastCompat.makeText(mContext, errText, Toast.LENGTH_SHORT).show();
            }
        }
    }

    //蓝牙打开结果
    private final BluetoothStateListener mBluetoothStateListener = new BluetoothStateListener() {
        @Override
        public void onBluetoothStateChanged(boolean openOrClosed) {
            if (AppManager.isForeground(BikeInUseRedActivity.this, "com.ekuaitu.kuaitu.activity.BikeInUseRedActivity")) {
                if (openOrClosed) {
                    BluetoothHelper.getInstance().searchDevice(mSearchResponse, commandCallback);
                } else {
                    rlProgressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, "蓝牙未开启", Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    private ProgressDialog pdSearch;
    private CountDownTimer searchTimer;

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

    //心跳计时
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    count++;
                    tvDuration.setText(TimeUtils.formatSecondCount(count + "", 1));
                    //app进入前台发送心跳
                    if (isSendHeat && heatCount % 600 == 0) {
                        //commitBikeLogHeatPre();
                        //sendHeat();
                    }
                    heatCount++;
                    break;
            }
            super.handleMessage(msg);
        }
    };

    //开锁进度框计时器
    private void countTime() {
        if (task == null) {
            task = new TimerTask() {
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendEmptyMessage(1);
                }
            };
        }
        if (timer == null) {
            timer = new Timer(true);
            timer.schedule(task, 0, 1000); //延时0ms后执行，1000ms执行一次
        }
        acquireWakeLock();
    }

    //开启设备电源锁
    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }

    //释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    //bike-APP端操作日志记录 操作前
    private void commitBikeLogPre() {
        NetUtils.commitBikeLog(BikeInUseRedActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "6", "1", "0", "", "");
    }

    //bike-APP端操作日志记录 操作成功
    private void commitBikeLogSuccess() {
        NetUtils.commitBikeLog(BikeInUseRedActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "6", "2", "0", "200", "");
    }

    //bike-APP端操作日志记录 操失败
    private void commitBikeLogFailed(int errorcode, String errormsg) {
        NetUtils.commitBikeLog(BikeInUseRedActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "6", "3", "4", errorcode + "", errormsg);
    }

    //bike-APP端操作日志记录 操作前 心跳
    private void commitBikeLogHeatPre() {
        NetUtils.commitBikeLog(BikeInUseRedActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "7", "1", "0", "", "");
    }

    //bike-APP端操作日志记录 操作成功 心跳
    private void commitBikeLogHeatSuccess() {
        NetUtils.commitBikeLog(BikeInUseRedActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "7", "2", "0", "200", "");
    }

    //bike-APP端操作日志记录 操失败 心跳
    private void commitBikeLogHeatFailed(int errorcode, String errormsg) {
        NetUtils.commitBikeLog(BikeInUseRedActivity.this, aMapLocation, bikeId, bikeLicense, lockType + "", orderId, "", "7", "3", "4", errorcode + "", errormsg);
    }

    /**
     * 进入围栏时的提示信息
     */
    private void showEnterGeofencePopupWindow() {
        View contentView = View.inflate(mContext, R.layout.popup_enter_geofence, null);
        popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int[] location = new int[2];
        mapView.getLocationInWindow(location);
        popupWindow.showAtLocation(mapView, Gravity.TOP | Gravity.RIGHT, 0, getResources().getDimensionPixelSize(R.dimen.toolbar_height) + DensityUtils.getStatusBarHeight(mContext) + 30);
    }

    /**
     * 围栏广播监听
     */
    private BroadcastReceiver mGeoFenceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
                //解析广播内容
                //获取Bundle
                Bundle bundle = intent.getExtras();
                //获取围栏行为：
                int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
                //获取自定义的围栏标识：
                String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
                //获取围栏ID:
                String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
                //获取当前有触发的围栏对象：
                GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
                switch (status) {
                    case GEOFENCE_IN:
                        Log.d("围栏广播监听", "进入了" + customId);
                        break;
                    case GEOFENCE_OUT:
                        Log.d("围栏广播监听", "出去了" + customId);
                        if (popupWindow != null) {
                            popupWindow.dismiss();
                        }
                        break;
                    case GEOFENCE_STAYED:
                        Log.d("围栏广播监听", "在围栏内停留了10分钟" + customId);
                        break;
                }
            }
        }
    };

    @Override
    public void onBackPressed() {
        exit();
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastCompat.makeText(this, "订单进行中，再按一次退出应用", Toast.LENGTH_LONG).show();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 3000);
        } else {
            releaseWakeLock();
            AppManager.getAppManager().AppExit(mContext);
        }
    }

    //蓝牙设备搜索结果
    private final SearchResponse mSearchResponse = new SearchResponse() {

        @Override
        public void onSearchStarted() {
            //progressBarBikeInUse.setVisibility(View.VISIBLE);
            rlProgressBar.setGravity(View.GONE);
            pdSearch = new ProgressDialog(BikeInUseRedActivity.this);
            pdSearch.setMessage("正在联系单车...");
            pdSearch.setCancelable(false);
            pdSearch.show();
            //调用show方法显示进度条对话框
            //使用匿名内部类实现线程并启动
            //对话框提示语，10秒后改变提示语
            searchTimer = new CountDownTimer(15000, 1000) {
                @Override
                public void onTick(long l) {
                    if (l >= 10000) {
                    } else {
                        pdSearch.setMessage("正在联系单车，请耐心等待...");
                    }
                }

                @Override
                public void onFinish() {
                    if (pdSearch != null) {
                        pdSearch.dismiss();
                    }
                }
            };
            searchTimer.start();
        }

        @Override
        public void onDeviceFounded(SearchResult device) {
            if (device.scanRecord[5] == 0x01 && device.scanRecord[6] == 0x02) {
                if (device.getAddress().equals(btMac)) {
                    pdSearch.setMessage("已找到单车，正在建立连接...");
                    power = device.scanRecord[14];
                    MyApplication.power = power;
                    BluetoothHelper.getInstance().connectDevice(btMac, loadPwd, loadKey, new BluetoothHelper.OnConnectListener() {
                        @Override
                        public void onConnectSuccess() {
                            ClientManager.getClient().stopSearch();
                            searchTimer.cancel();
                            searchTimer = null;
                        }

                        @Override
                        public void onConnectFailed() {
                            ToastCompat.makeText(BikeInUseRedActivity.this, "连接设备失败", Toast.LENGTH_SHORT).show();
                            if (pdSearch != null) {
                                pdSearch.dismiss();
                            }
                            commitBikeLogFailed(0, "inUse连接失败");
                        }
                    });
                }
            }
        }

        @Override
        public void onSearchStopped() {
            commitBikeLogFailed(0, "未扫描到该单车，请将手机靠近车锁再试");
            ToastCompat.makeText(BikeInUseRedActivity.this, "未找到该单车", Toast.LENGTH_SHORT).show();
            //未搜索到蓝牙
            rlProgressBar.setVisibility(View.GONE);
            if (pdSearch != null) {
                pdSearch.dismiss();
            }
            searchTimer.cancel();
            searchTimer = null;
            if (caozuo == 0) {
                caozuo = -1;
                dropOffBTBike("", btMac, "1");
            }
        }

        @Override
        public void onSearchCanceled() {
            if (pdSearch != null) {
                pdSearch.dismiss();
            }
            //搜索到后执行此方法，此时已经发起连接
            rlProgressBar.setVisibility(View.GONE);
        }
    };

    /**
     * 蓝牙指令响应回调
     */
    private BluetoothHelper.BluetoothCommandCallback commandCallback = new BluetoothHelper.BluetoothCommandCallback() {
        @Override
        public void onSetReturnMode(boolean isSuccessful) {
            if (isSuccessful) {
                rlProgressBar.setVisibility(View.GONE);
                if (pdSearch != null) {
                    pdSearch.dismiss();
                }
                dropOffBTBike(power + "", btMac, "0");
            } else {
                rlProgressBar.setVisibility(View.GONE);
                if (pdSearch != null) {
                    pdSearch.dismiss();
                }
                dropOffBTBike(power + "", btMac, "0");
            }
        }

        @Override
        public void onGetToken(byte[] btToken) {
            MyApplication.btToken = btToken;
            if (pdSearch != null) {
                pdSearch.dismiss();
            }
            if (isReturnBike) {
                isReturnBike = false;
                BluetoothHelper.getInstance().checkStatus();
            }
        }

        @Override
        public void onOpenLock(boolean isSuccessful) {

        }

        @Override
        public void onCloseLock(boolean isSuccessful) {
            closeLockSendLocation();
        }

        @Override
        public void onResetLock(boolean isSuccessful) {

        }

        @Override
        public void onGetLockPower(byte power) {
            BikeInUseRedActivity.this.power = power;

            if (lockType == 4 && isReturnBike) {
                //不可充电的锁，设置还车模式
                BluetoothHelper.getInstance().setReturnStatus();
            } else if (isReturnBike) {   //其他蓝牙锁，不设置还车模式，直接还车
                rlProgressBar.setVisibility(View.GONE);
                if (pdSearch != null) {
                    pdSearch.dismiss();
                }
                //由于发送一次查询电量的指令 onGetLockPower()这个方法会调用多次，为了避免多次调用还车接口所以用isStartingDropOffBike这个变量做个标记
                if (!isStartingDropOffBike) {
                    isStartingDropOffBike = true;
                    dropOffBTBike(power + "", btMac, "0");
                }
            }
        }

        @Override
        public void onCheckLockStatus(boolean isOpen) {
            if (isOpen) {
                isReturnBike = false;
                rlProgressBar.setVisibility(View.GONE);
                if (pdSearch != null) {
                    pdSearch.dismiss();
                }
                final KuaituDialog kuaituDialog = new KuaituDialog(BikeInUseRedActivity.this);
                kuaituDialog.setTitle(getString(R.string.dialogTitle));
                kuaituDialog.setMessage("请您关闭车锁后再点“还车”进行结算");
                kuaituDialog.setYesOnclickListener("确定", new KuaituDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setNoOnclickListener("取消", new KuaituDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        kuaituDialog.dismiss();
                    }
                });
                kuaituDialog.setCancelable(false);
                kuaituDialog.show();
            } else {
                //查询电量
                BluetoothHelper.getInstance().checkDianLiang();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (btMac != null) {
            ClientManager.getClient().disconnect(btMac);
        }

        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (task != null) {
            task.cancel();
            task = null;
        }

        if (searchTimer != null) {
            searchTimer.cancel();
            searchTimer = null;
        }
        unregisterReceiver(mGeoFenceReceiver);
    }
}
